package com.epam.rentcar.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.NamingException;

import com.epam.rentcar.transferobjects.User;
import com.epam.rentcar.utils.dbconn.ConnEstablisher;
import com.epam.rentcar.utils.dbconn.ConnectionFactory;

public class UserDAOImpl implements UserDAO {

	ConnEstablisher connEstablisher;
	
	public UserDAOImpl(int wichConnection){
		connEstablisher = ConnectionFactory.getConnection(wichConnection);
	}
	
	public User getUser(String role, String login, String password) throws SQLException, NamingException {

		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;

		User user = new User();

		try {

			connection = connEstablisher.getConnection();

			pstmt = connection.prepareStatement("SELECT * FROM ADMIN.USERS " +
					"WHERE ROLE=?" +
					"AND LOGIN=? " +
					"AND PASSWORD=?");
			pstmt.setString(1, role);
			pstmt.setString(2, login);
			pstmt.setString(3, password);
			pstmt.execute();

			resultSet = pstmt.getResultSet();

			if (resultSet.next()) {
				user.setID(resultSet.getInt("id"));
				user.setLogin(login);
				user.setRole(role);
				return user;
			} else {
				return user;
			}

		} finally {
			connection.close();
		} 
	}

	public boolean addUser(String login, String password) throws SQLException, NamingException {

		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;

		try {

			connection = connEstablisher.getConnection();

			pstmt = connection.prepareStatement("SELECT * FROM ADMIN.USERS " +
					"WHERE LOGIN=?");
			pstmt.setString(1, login);
			pstmt.execute();

			resultSet = pstmt.getResultSet();

			if (resultSet.next()) {
				return false;	
			}

			pstmt = connection.prepareStatement("INSERT INTO ADMIN.USERS " +
					"(ROLE, LOGIN, PASSWORD) VALUES (?, ?, ?)");

			pstmt.setString(1, "user");
			pstmt.setString(2, login);
			pstmt.setString(3, password);
			pstmt.execute();

			return true;

		} finally {
			connection.close();
		}
	}

	public User getUser(int userID) throws SQLException, NamingException {

		Connection connection = null;
		PreparedStatement pstmt = null;
		ResultSet resultSet = null;

		User user = new User();

		try {

			connection = connEstablisher.getConnection();

			pstmt = connection.prepareStatement("SELECT * FROM ADMIN.USERS " +
					"WHERE ID=?");
			pstmt.setInt(1, userID);
			pstmt.execute();

			resultSet = pstmt.getResultSet();

			if (resultSet.next()) {
				user.setID(resultSet.getInt("id"));
				user.setLogin(resultSet.getString("login"));
			}
			
			return user;
			
		} finally {
			connection.close();
		} 
	}

}
